<template>
    <div>
        <div class="title">锚点、组件按需加载</div>
        <div class="top-anchor">
            <div
                class="item"
                v-for="(item, index) in list"
                :key="item.id"
                :class="{ active: activeId === item.id }"
                @click="onAnchor(index)"
            >
                title-{{ item.title }}
            </div>
        </div>
        <div
            v-for="(item, index) in list"
            :key="item.id"
            :ref="(el) => getRefDom(el, index)"
        >
            <Observer :data-id="item.id" @show="(val) => (item.show = val)">
                <div class="content">
                    {{ item.title }}
                </div>
            </Observer>
            <!-- <div class="content">
                    {{ item.title }}
                </div> -->
        </div>
    </div>
</template>
<script setup>
import { computed, ref, inject } from "vue";
import Observer from "@/common/Observer/index.vue";

const global = inject("global");

const refsList = ref([]);
const getRefDom = (el, index) => {
    if (el) {
        refsList.value[index] = el;
    }
};

const list = ref([
    { id: 1, title: "1", show: false },
    { id: 2, title: "2", show: false },
    { id: 3, title: "3", show: false },
    { id: 4, title: "4", show: false },
    { id: 5, title: "5", show: false },
    { id: 6, title: "6", show: false },
    { id: 7, title: "7", show: false },
    { id: 8, title: "8", show: false },
]);

const activeId = computed(() => {
    let obj = list.value.find((v) => v.show);
    return obj ? obj.id : null;
});

const onAnchor = (index) => {
    let dom = refsList.value;
    let offsetTop = dom[index].offsetTop;
    global.$emitter.emit("RouterScroll", offsetTop - 50);
};
</script>
<style lang="less" scoped>
.title {
    margin-bottom: 8px;
}
.top-anchor {
    display: flex;
    flex-wrap: wrap;
    gap: 8px 8px;
    position: sticky;
    top: 0;
    background: var(--bg-color-1);
    padding-bottom: 10px;
    .item {
        line-height: 28px;
        padding: 0 12px;
        border-radius: 2px;
        border: 1px solid var(--border-color);
        cursor: pointer;
        &.active {
            background: #0052D9;
            border-color: #0052D9;
            color: #fff;
        }
    }
}
.content {
    height: 300px;
    background: var(--bg-color-2);
    margin-bottom: 30px;
    padding: 24px;
}
</style>
